package com.sofian.chat.server;

import java.util.ArrayList;
import java.util.Date;



import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.sofian.chat.client.ChatMessageService;
import com.sofian.chat.client.ChatMessage;

public class ChatMessageServiceServlet extends RemoteServiceServlet implements ChatMessageService {
	private static ArrayList<ChatMessage> messages = MessageShare.getMessages();

	@Override
	public ChatMessage[] getNewMessages(long since) {
		synchronized(messages) {
			int index = messages.size() - 1;
			int count = 0;
			while(index >= 0) {
				if(messages.get(index).getTimestamp() > since) {
					count++;
					index--;
				} else {
					break;
				}
			}
			ChatMessage[] array = new ChatMessage[0];
			if(count > 0) {
				return messages.subList(messages.size() - count, messages.size()).toArray(array);
			} else {
				return array;
			}
			
		}
	}
	
	public ChatMessage[] waitNewMessages(long since, int timeout) {
		synchronized(messages) {
			ChatMessage[] array = getNewMessages(since);
			if(array.length == 0) {
				try {
					messages.wait(timeout);
				} catch(InterruptedException ie) {
				}
				array = getNewMessages(since);
			}
			return array;
		}
	}

	@Override
	public void sendMessage(String sender, String message) {
	    System.out.println(sender + ": " + message);
		synchronized(messages) {
			messages.add(new ChatMessage(new Date().getTime(), sender, message));
			MessageShare.addMessages(messages);
			messages.notify();
			
		}
	}
	
	
}
